package com.mgm.affiliate.service.impl;

import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mgm.affiliate.service.AffiliateService;
import com.mgm.constant.APICode;
import com.mgm.constant.GobalConstant;
import com.mgm.dao.AffiliateMapper;
import com.mgm.page.DataGrid;
import com.mgm.pojo.Advertisement;
import com.mgm.pojo.Affiliate;
import com.mgm.pojo.AffiliateExample;
import com.mgm.pojo.AffiliateExample.Criteria;
import com.mgm.result.IMessage;
import com.mgm.utils.RandomCodeUtils;
import com.mgm.utils.UUIDUtil;

/**
 * 
 * @ClassName: AffiliateServiceImpl 
 * @Description: TODO(...) 
 * @author Andy Zhang
 * @date 2018年6月28日 下午8:54:33 
 *
 */
@Service
public class AffiliateServiceImpl implements AffiliateService {
	
	/** 默认渠道溢价等于0 */
	protected final Integer SHAVE = 0; 

	@Autowired
	private AffiliateMapper affiliateMapper;
	
	private Lock lock = new ReentrantLock();
	
	@Override
	public IMessage addAffiliate(Affiliate affiliate) {
		
		if (affiliate.getEnabled() == null) affiliate.setEnabled(false);
		if (affiliate.getShave() == null) affiliate.setShave(SHAVE);
		affiliate.setToken(UUIDUtil.uuidRep());
		
		// 获取所有渠道Id
		List<String> advIdArr = affiliateMapper.selectAffIds();
		//加锁......
		lock.lock();
		try {
			// 数据库中渠道ID与随机生成4位数（阿拉伯数字）进行比较
			boolean isExist = true;
			String code = null;
			while (isExist) {
				code = GobalConstant.AFF_PRE + RandomCodeUtils.randomNumeric(4);
				isExist = advIdArr.contains(code);
			}
			affiliate.setAffId(code);
			affiliateMapper.insert(affiliate);
		} finally {
			lock.unlock(); // 释放锁......
		}
		
		return IMessage.success();
	}

	@Override
	public IMessage deleteAffiliate(Affiliate affiliate) {
		affiliateMapper.deleteByPrimaryKey(affiliate.getId());
		return IMessage.success();
	}

	@Override
	public IMessage deleteById(List<Integer> ids) {
		for (Integer id : ids) {
			affiliateMapper.deleteByPrimaryKey(id);
		}
		return IMessage.success();
	}

	@Override
	public IMessage updateAffiliate(Affiliate affiliate) {
		affiliateMapper.updateByPrimaryKeySelective(affiliate);
		return IMessage.success();
	}

	@Override
	public IMessage isEnabled(Integer id, Boolean enabled) {
		Affiliate record = new Affiliate();
		record.setId(id);
		record.setEnabled(enabled);
		affiliateMapper.updateByPrimaryKeySelective(record);
		return IMessage.success();
	}
	
	@Override
	public IMessage modifyShave(Integer id, Integer shave) {
		Affiliate record = new Affiliate();
		record.setId(id);
		record.setShave(shave);
		affiliateMapper.updateByPrimaryKeySelective(record);
		return IMessage.success();
	}
	
	@Override
	public IMessage modifyInitialShave(Integer id) {
		Affiliate adment = affiliateMapper.selectByPrimaryKey(id);
		Affiliate record = new Affiliate();
		record.setId(id);
		record.setShave(0); //默认0
		affiliateMapper.updateByPrimaryKeySelective(record);
		return IMessage.success();
	}

	@Override
	public Affiliate selectById(Integer id) {
		return affiliateMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Affiliate> findAllByEnabled() {
		AffiliateExample example = new AffiliateExample();
		Criteria criteria = example.createCriteria();
		criteria.andEnabledEqualTo((byte) 1);
		criteria.andPostBackIsNotNull();
		return affiliateMapper.selectByExample(example);
	}

	@Override
	public DataGrid findAll(Map<String, String> param, Integer pageNum, Integer pageSize) {
		//查询
		AffiliateExample example = new AffiliateExample();
		//分页处理
		PageHelper.startPage(pageNum, pageSize);
		//创建条件
		Criteria criteria = example.createCriteria();
		String account = param.get("account");
		String affId = param.get("aff_id");
		String name = param.get("name");
		String enabled = param.get("enabled");
		
		if(!StringUtils.isEmpty(account)) {
			criteria.andAccountLike("%" + account + "%");
		}
		if(!StringUtils.isEmpty(affId)) {
			criteria.andAffIdLike("%" + affId + "%");
		}
		if(!StringUtils.isEmpty(name)) {
			criteria.andNameLike("%" + name + "%");
		}
		if(!StringUtils.isEmpty(enabled)) {
			criteria.andEnabledEqualTo(enabled.equals("true") ? (byte)1 : (byte) 0);
		}
		
		List<Affiliate> list = affiliateMapper.selectByExample(example);
		//创建一个返回值对象
		DataGrid dataGrid = new DataGrid();
		dataGrid.setItems(list);
		//获取PageInfo相关信息
		PageInfo<Affiliate> pageInfo = new PageInfo<>(list);
		dataGrid.setTotal_count(pageInfo.getTotal()); //总记录数
		dataGrid.setPage_count(pageInfo.getPages()); // 总页数
		dataGrid.setPage_index(pageInfo.getPageNum()); // 当前页
		
		return dataGrid;
	}

	@Override
	public List<Affiliate> findByName(String name) {
		AffiliateExample example = new AffiliateExample();
		Criteria criteria = example.createCriteria();
		criteria.andNameEqualTo(name);
		return affiliateMapper.selectByExample(example);
	}

	@Override
	public IMessage findByAffId(String affId, String token) {
		Affiliate affiliate = affiliateMapper.selectByAffIdAndToken(affId, token);
		if(affiliate == null) {
			return IMessage.error("affid or token is incorrect.");
		}
		return IMessage.success();
	}

	@Override
	public Affiliate findByAffId(String affId) {
		AffiliateExample example = new AffiliateExample();
		Criteria criteria = example.createCriteria();
		criteria.andAffIdEqualTo(affId);
		List<Affiliate> list = affiliateMapper.selectByExample(example);
		if(CollectionUtils.isEmpty(list)) {
			return null;
		} else {
			return list.get(0);
		}
		
	}

}
